package net.member.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemberDAO {
	Connection con;
	PreparedStatement pstmt;
	ResultSet rs;
	DataSource ds;
	
	public MemberDAO() {
		try{
			Context init=new InitialContext();
			ds=(DataSource)init.lookup("java:comp/env/jdbc/OracleDB");
		}catch(Exception ex){
			System.out.println("DB연결 실패 : " + ex);
			return;
		}
	}
	
	// 멤버 추가
	public boolean joinMember(MemberBean member){
		String sql="INSERT INTO MEMBER VALUES (?,?,?,sysdate)";
		int result=0;
		
		try{
			con=ds.getConnection();
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, member.getMember_email());
			pstmt.setString(2, member.getMember_password());
			pstmt.setString(3, member.getMember_brief_address());
			result=pstmt.executeUpdate();
			if(result!=0){
				return true;
			}
		}catch(Exception ex){
			System.out.println("joinMember 에러 : " + ex);
		}finally{
			if(rs!=null) try{rs.close();}catch(SQLException ex){}
			if(pstmt!=null) try{pstmt.close();}catch(SQLException ex){}
			if(con!=null) try{con.close();}catch(SQLException ex){}
		}
		return false;
	}
	
	// 로그인 시에 멤버가 맞는지 확인
	public int isMember(MemberBean member){
		String sql="SELECT member_password FROM member WHERE member_email=?";
		int result=-1; // -1 : 이메일 없음, 0 : 패스워드 불일치, 1 : 패스워드 일치
		
		try{
			con=ds.getConnection();
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, member.getMember_email());
			rs=pstmt.executeQuery();
			
			if(rs.next()){
				if(rs.getString("member_password").equals(member.getMember_password())){
					result=1;
				}else{
					result=0;
				}
			}else{
				result=-1;
			}
		}catch(Exception ex){
			System.out.println("isMember 에러 : " + ex);
		}finally{
			if(rs!=null) try{rs.close();}catch(SQLException ex){}
			if(pstmt!=null) try{pstmt.close();}catch(SQLException ex){}
			if(con!=null) try{con.close();}catch(SQLException ex){}
		}
		
		return result;
	}
}
